﻿using System.Text;
using Microsoft.SharePoint;

namespace Eneta.Portal.Common
{
    public class Query
    {
        public static SPListItemCollection GetItems(SPList list, string queryString, uint resultCount, string[] fields)
        {
            var query = new SPQuery
                            {
                                RowLimit = resultCount, 
                                Query = queryString
                            };

            var viewFields = GetFields(list, fields);
            if (!string.IsNullOrEmpty(viewFields))
                query.ViewFields = viewFields;
            if (list == null)
                return null;
            return list.GetItems(query);
        }

        public static SPListItem GetItem(SPList list, string fieldName, object value)
        {
            var field = list.Fields.GetFieldByInternalName(fieldName);
            var type = field.TypeAsString;

            var queryString = "<Where><Eq><FieldRef Name='{0}' /><Value Type='{1}'>{2}</Value></Eq></Where>";
            queryString = string.Format(queryString, fieldName, type, value);

            var query = new SPQuery();
            query.Query = queryString;
            query.RowLimit = 1;

            var items = list.GetItems(query);
            if (items == null)
                return null;
            if (items.Count == 0)
                return null;
            return items[0];
        }

        private static string GetFields(SPList list, string[] fields)
        {
            if (fields.Length == 0)
                return string.Empty;
            var result = new StringBuilder();
            foreach (string fieldName in fields)
            {
                if (!list.HasField(fieldName))
                    return string.Empty;
                var field = list.Fields.GetFieldByInternalName(fieldName);
                if (field == null)
                    continue;
                result.Append("<FieldRef Name='" + field.InternalName + "'/>");
            }
            if (result.Length == 0)
                return string.Empty;
            return result.ToString();
        }
    }
}
